package com.yhsoft.buyer.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yhsoft.benefitcard.entity.BatchGoods;
import com.yhsoft.benefitcard.entity.CardsInfo;
import com.yhsoft.benefitcard.service.IBatchGoodsService;
import com.yhsoft.benefitcard.service.ICardsInfoService;
import com.yhsoft.buyer.controller.Po.SkuPo;
import com.yhsoft.buyer.controller.request.CartInVo;
import com.yhsoft.buyer.controller.response.CartOutVo;
import com.yhsoft.buyer.entity.BuyerCart;
import com.yhsoft.buyer.entity.BuyerCartSku;
import com.yhsoft.buyer.mapper.BuyerCartMapper;
import com.yhsoft.buyer.mapper.BuyerCartSkuMapper;
import com.yhsoft.buyer.service.IBuyerCartService;
import com.yhsoft.common.service.TokenService;
import com.yhsoft.common.utils.IDGenerator;
import com.yhsoft.common.vo.Result;
import com.yhsoft.goods.entity.*;
import com.yhsoft.goods.mapper.CompanyGoodsMapper;
import com.yhsoft.goods.mapper.CompanySkuChargeMapper;
import com.yhsoft.goods.mapper.GoodsInfoMapper;
import com.yhsoft.goods.mapper.SkuInfoMapper;
import com.yhsoft.goods.service.IGoodSkuService;
import com.yhsoft.wxprogram.controller.response.BenefitCardOutVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 购物车 服务实现类
 * </p>
 *
 * @author yyyyyyyh
 * @since 2023-09-26
 */
@Service
@Slf4j
public class BuyerCartServiceImpl extends ServiceImpl<BuyerCartMapper, BuyerCart> implements IBuyerCartService {

    @Resource
    private GoodsInfoMapper goodsInfoMapper;

    @Resource
    private SkuInfoMapper skuInfoMapper;

    @Resource
    private IGoodSkuService iGoodSkuService;

    @Resource
    private BuyerCartSkuMapper buyerCartSkuMapper;

    @Resource
    private CompanyGoodsMapper companyGoodsMapper;

    @Resource
    private IBatchGoodsService iBatchGoodsService;

    @Resource
    private ICardsInfoService iCardsInfoService;

    @Resource
    private CompanySkuChargeMapper companySkuChargeMapper;

    @Override
    public Result<?> addToCart(CartInVo inVo, boolean isFastAdd) {

        String userId = TokenService.getUserBytoken().getId();

        // 判断此用户现有购物车中是否有同个商品，有的话将此次sku加入到查询到的购物车
        LambdaQueryWrapper<BuyerCart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(BuyerCart::getUserId, userId);
        wrapper.eq(BuyerCart::getCartStatus, 0);
        wrapper.eq(BuyerCart::getGoodsId, inVo.getGoodsId());
        BuyerCart cart = this.baseMapper.selectOne(wrapper);

        if (cart == null || isFastAdd) {
            // 没有的话，插入
            String cartNum = IDGenerator.generate20("CART");

            BuyerCart buyerCart = new BuyerCart();
            BeanUtils.copyProperties(inVo, buyerCart);
            buyerCart.setUserId(userId);
            buyerCart.setCartNum(cartNum);

            int i = this.baseMapper.insert(buyerCart);
            if (i > 0) {
                // 获取到刚刚插入的购物车的id
                LambdaQueryWrapper<BuyerCart> shoppingCartQueryWrapper = new LambdaQueryWrapper<>();
                shoppingCartQueryWrapper.eq(BuyerCart::getCartNum, cartNum);
                BuyerCart shoppingCart = this.baseMapper.selectOne(shoppingCartQueryWrapper);
                Integer cartId = shoppingCart.getCartId();

                // 插入商品子项
                BuyerCartSku sku = new BuyerCartSku();
                BeanUtils.copyProperties(inVo, sku);
                sku.setUserId(userId);
                sku.setCartId(cartId);

                // 记录商品原价
                SkuInfo skuInfo = skuInfoMapper.selectById(inVo.getSkuId());
                if (skuInfo != null) {
                    sku.setOriginalPrice(skuInfo.getSkuPrice());
                }

                i = buyerCartSkuMapper.insert(sku);
                if (i > 0) {
                    return Result.success("添加购物车成功!购物车id：" + cartId);
                } else {
                    // 插入子项失败，删除购物车
                    this.baseMapper.deleteById(cartId);
                }
            } else {
                return Result.fail("添加购物车失败");
            }
        }
        // 已经存在此商品的购物车，只插入子项
        Integer cartId = cart.getCartId();
        // 插入商品子项
        // 判断子项是否存在，若存在，数量+1
        LambdaQueryWrapper<BuyerCartSku> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(BuyerCartSku::getUserId, userId);
        wrapper1.eq(BuyerCartSku::getCartId, cartId);
        wrapper1.eq(BuyerCartSku::getSkuId, inVo.getSkuId());

        BuyerCartSku cartSku = buyerCartSkuMapper.selectOne(wrapper1);
        if (cartSku == null) {
            BuyerCartSku sku = new BuyerCartSku();
            BeanUtils.copyProperties(inVo, sku);
            sku.setUserId(userId);
            sku.setCartId(cartId);

            int i = buyerCartSkuMapper.insert(sku);
            if (i > 0) {
                return Result.success("添加购物车成功!购物车id：" + cartId);
            } else {
                return Result.fail("添加购物车失败");
            }
        }

        // 已存在sku子项，数量+1
        cartSku.setSkuQuantity(cartSku.getSkuQuantity() + inVo.getSkuQuantity());
        buyerCartSkuMapper.updateById(cartSku);
        return Result.success("添加购物车成功!购物车id：" + cartId);

    }

    @Override
    public List<CartOutVo> getCart() {
        // 查询购物车主表
        LambdaQueryWrapper<BuyerCart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(BuyerCart::getUserId, TokenService.getUserBytoken().getId());
        wrapper.eq(BuyerCart::getCartStatus, 0);
        // 只显示积分卡有余额且未冻结的记录
        wrapper.inSql(BuyerCart::getGoodsId, "SELECT DISTINCT(goods_id) FROM `benefit_batch_goods` " +
                "where second_bantch_num in (select second_bantch_num from benefit_cards_info " +
                "where balance > 0 and is_enable = 0 and user_id = '" + TokenService.getUserBytoken().getId() + "')");
        List<BuyerCart> buyerCart = this.baseMapper.selectList(wrapper);

        if (buyerCart.size() == 0) {
            return null;
        }

        List<CartOutVo> outVos = BeanUtil.copyToList(buyerCart, CartOutVo.class);
        // 循环拼接购物车子项信息
        outVos.forEach(a -> {
            LambdaQueryWrapper<BuyerCartSku> wrapper1 = new LambdaQueryWrapper<>();
            wrapper1.eq(BuyerCartSku::getCartId, a.getCartId());

            List<BuyerCartSku> cartSku = buyerCartSkuMapper.selectList(wrapper1);
            if (cartSku.size() == 0) {
                return;
            }

            GoodsInfo goodsInfo = goodsInfoMapper.selectById(a.getGoodsId());
            a.setGoodsName(goodsInfo.getGoodsName());

            // 获取渠道商商品商城加价
            LambdaQueryWrapper<CompanySkuCharge> wrapper3 = new LambdaQueryWrapper<>();
            wrapper3.eq(CompanySkuCharge::getCompanyId, TokenService.getUserBytoken().getCompanyId())
                    .eq(CompanySkuCharge::getGoodsId, a.getGoodsId());
            List<CompanySkuCharge> chargeList = companySkuChargeMapper.selectList(wrapper3);
            Map<Integer, BigDecimal> chargeMap = null;
            if (chargeList.size() > 0) {
                chargeMap = chargeList.stream().collect(Collectors.toMap(CompanySkuCharge::getSkuInfoId, CompanySkuCharge::getMallAddPrice));
            }

            // 获取服务费和加价
            BigDecimal charge = getCharge(a.getGoodsId());
            BigDecimal addPrice = getAddPrice_new(a.getGoodsId());

            Map<Integer, BigDecimal> finalChargeMap = chargeMap;
            List<SkuPo> skuPoList = cartSku.stream().map(
                    e -> {
                        // 查询sku具体信息
                        SkuInfo skuInfo = skuInfoMapper.selectById(e.getSkuId());
                        GoodSku goodSku = iGoodSkuService.getById(skuInfo.getSkuNameId());
                        // 填充子项信息
                        SkuPo po = new SkuPo();
                        po.setCartSkuId(e.getId());
                        po.setPicUrl(goodsInfo.getPicUrl());

                        // 计算价格
                        // 有建议售价取建议售价，没建议售价，取结算成本
                        BigDecimal price = skuInfo.getAdvocatePrice() == null ? skuInfo.getSkuPrice().multiply(BigDecimal.ONE.add(charge)) : skuInfo.getAdvocatePrice();
                        BigDecimal addMallPrice = finalChargeMap == null ? BigDecimal.ZERO : finalChargeMap.getOrDefault(skuInfo.getId(), BigDecimal.ZERO);
                        log.info(a.getGoodsName() + "-" + skuInfo.getSkuInfo() + ",商品商城加价：" + addMallPrice);
                        BigDecimal sumPrice = price.add(addMallPrice).add(addPrice);

                        if (skuInfo.getAdvocatePrice() == null) {
                            log.info(a.getGoodsName() + "-" + skuInfo.getSkuInfo() + ",建议售价为空，取结算成本：" + skuInfo.getSkuPrice().multiply(BigDecimal.ONE.add(charge)) + "元");
                            log.info(a.getGoodsName() + "-" + skuInfo.getSkuInfo() + ",最终售价是：" +
                                    "结算成本(" + skuInfo.getSkuPrice().multiply(BigDecimal.ONE.add(charge)) + ")+商城加价(" + addMallPrice + ") +最终福利卡加价(" + addPrice + ")=" + sumPrice + "元");
                        } else {
                            log.info(a.getGoodsName() + "-" + skuInfo.getSkuInfo() + ",建议售价不为空，取建议售价：" + skuInfo.getAdvocatePrice() + "元");
                            log.info(a.getGoodsName() + "-" + skuInfo.getSkuInfo() + ",最终售价是：" +
                                    "建议售价(" + skuInfo.getAdvocatePrice() + ")+商城加价(" + addMallPrice + ") +最终福利卡加价(" + addPrice + ")=" + sumPrice + "元");
                        }

                        po.setGoodsPrice(sumPrice);
                        po.setDescription(goodSku.getSkuName() + " " + skuInfo.getSkuInfo());
                        po.setSkuId(skuInfo.getId());
                        po.setSkuNameId(skuInfo.getSkuNameId());
                        po.setSkuQuantity(e.getSkuQuantity());
                        return po;
                    }
            ).collect(Collectors.toList());
            a.setSkuPos(skuPoList);
        });

        return outVos;
    }

    private BigDecimal getCharge(Integer goodsId) {
        // 获取服务费
        LambdaQueryWrapper<CompanyGoods> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(CompanyGoods::getCompanyId, TokenService.getUserBytoken().getCompanyId());
        wrapper1.eq(CompanyGoods::getGoodsId, goodsId);
        List<CompanyGoods> companyGoodsList = companyGoodsMapper.selectList(wrapper1);
        BigDecimal charge = BigDecimal.ZERO;
        if (companyGoodsList.size() > 0 && StringUtils.hasLength(companyGoodsList.get(0).getCustomCharge())) {
            charge = new BigDecimal(companyGoodsList.get(0).getCustomCharge()).divide(new BigDecimal(100));
        }
        return charge;
    }

    private BigDecimal getAddPrice(Integer goodsId) {
        BigDecimal addPrice = BigDecimal.ZERO;
        // 获取加价
        BenefitCardOutVo cardsInfo = iCardsInfoService.getInUseCard();
        if (cardsInfo == null) {
            return addPrice;
        }
        CardsInfo cardsInfo1 = iCardsInfoService.getById(cardsInfo.getId());
        String batch2Num = cardsInfo1.getSecondBantchNum();
        LambdaQueryWrapper<BatchGoods> wrapper2 = new LambdaQueryWrapper<>();
        wrapper2.eq(BatchGoods::getSecondBantchNum, batch2Num);
        wrapper2.eq(BatchGoods::getGoodsId, goodsId);
        List<BatchGoods> batchGoods = iBatchGoodsService.list(wrapper2);
        if (batchGoods.size() > 0) {
            addPrice = batchGoods.get(0).getAddPrice();
        }
        return addPrice;
    }

    private BigDecimal getAddPrice_new(Integer goodsId) {
        // 获取最高加价
        BigDecimal addPrice = BigDecimal.ZERO;

        QueryWrapper<BatchGoods> wrapper2 = new QueryWrapper<>();
        wrapper2.inSql("second_bantch_num",
                "select second_bantch_num from benefit_cards_info where balance > 0 and is_enable = 0 and user_id = '"
                        + TokenService.getUserBytoken().getId() + "'");
        wrapper2.eq("goods_id", goodsId);
        List<BatchGoods> batchGoods = goodsInfoMapper.getGoodsMaxPrice(wrapper2);
        batchGoods.remove(null);
        if (batchGoods.size() > 0) {
            addPrice = batchGoods.get(0).getAddPrice();
        }
        log.info("商品id：" + goodsId + "，加价：" + addPrice);
        return addPrice;
    }


}
